<?php

class NBC
{
	protected $db;
	protected $very;
	
	public function __construct()
	{
		global $very, $db;
		$this->db = $db;
		$this->very = $very;
	}
	
	public function init($url)
	{
		try {
			$service = new SoapClient($url, array('encoding'=>'gbk'));
		}
		catch (Exception $e)
		{
			Showmsg('无法正确请求NBC用户同步网址' . $url);	
		}
		$xmlString = $service->__soapCall('GetUserListAll', array());
		$xmlString = iconv('gbk', 'utf-8', $xmlString);
		$xml = simplexml_load_string($xmlString);
		
		$addNum = $updateNum = 0;

		foreach ($xml as $line)
		{
			$nbcId = $line->userid;
			$userpwd = $line->userpwd;
			//echo $userpwd . "... " . strlen($userpwd) . "<BR>";
			$username = $line->username;
			
			if (empty($username)) {
				continue;
			}
			
			$email = $line->email;
			$telephone = $line->telephone;
			
			if (strlen(trim($userpwd)) > 0) {
				$pwdSQL = ",password='" . md5($userpwd) . "'";
			} else {
				$pwdSQL = ",password=''";
			}
			
			$rs = $this->db->query("SELECT uid FROM cms_user WHERE nbcid='$nbcId'");
			if (mysql_num_rows($rs) == 0) {
				$this->db->query("INSERT cms_user SET username='$username',realname='$username',telephone='$telephone',email='$email',nbcid='$nbcId'$pwdSQL");
				$addNum++;
			} else {
				$this->db->query("UPDATE cms_user SET username='$username',realname='$username',telephone='$telephone',email='$email'$pwdSQL WHERE nbcid='$nbcId'");
				$updateNum++;			
			}
		}
		//exit;
		return array($addNum, $updateNum);
	}
	
	public function modify()
	{
		$type = array(
			'name'=>'username',
			'password'=>'password',
			'phone'=>'telephone',
			'email'=>'email'
		);
		//writeover(D_P . 'data/nbc_debug.txt', var_export($_POST, true) . "\r\n", 'ab');
		
		if (isset($_POST['id'])) {
			$nbcid = $_POST['id'];
			foreach ($_POST as $key => $val)
			{
				if (key_exists($key, $type)) {
					if ($key == 'password') {
						$val = md5($val);
					}
					$sqlAdd[] = "$type[$key]='$val'";
				}
			}
		} else {
			$nbcid = $_GET['id'];
			foreach ($_GET as $key => $val)
			{
				if (key_exists($key, $type)) {
					if ($key == 'password') {
						$val = md5($val);
					}
					$sqlAdd[] = "$type[$key]='$val'";
				}
			}			
		}
		if (empty($sqlAdd) || empty($nbcid)) {
			return ;
		}
		$sqlString = implode(' , ', $sqlAdd);
		$this->db->query("UPDATE cms_user SET $sqlString WHERE nbcid='$nbcid'");
		writeover(D_P . 'data/nbc_debug.txt', "UPDATE cms_user SET $sqlString WHERE nbcid='$nbcid'" . "\r\n", "ab");
		echo 'OK';
		exit;
	}
}


?>